/*
 * Copyright (c) 2020. Bailiang All rights reserved. 广州百量科技有限公司 版权所有
 * 请勿修改或删除版权声明及文件头部.
 */

package top.hundreds.oasys.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import top.hundreds.common.crud.bean.BaseEntityFieldName;
import top.hundreds.oasys.utils.MvcHttpUtil;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充
 *
 * @author 陈华强
 * @since 1.0
 */
@Component
@Slf4j
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            Long userId = MvcHttpUtil.getCurrAdminId();
            if (metaObject.hasSetter(BaseEntityFieldName.CREATE_BY) && metaObject.hasGetter(BaseEntityFieldName.CREATE_BY)) {
                this.setFieldValByName(BaseEntityFieldName.CREATE_BY, userId, metaObject);
            }
            if (metaObject.hasSetter(BaseEntityFieldName.UPDATE_BY) && metaObject.hasGetter(BaseEntityFieldName.UPDATE_BY)) {
                this.setFieldValByName(BaseEntityFieldName.UPDATE_BY, userId, metaObject);
            }
        } catch (Exception ignored) {
        }
        if (metaObject.hasSetter(BaseEntityFieldName.CREATE_TIME) && metaObject.hasGetter(BaseEntityFieldName.CREATE_TIME)) {
            this.setFieldValByName(BaseEntityFieldName.CREATE_TIME, new Date(), metaObject);
        }
        if (metaObject.hasSetter(BaseEntityFieldName.UPDATE_TIME) && metaObject.hasGetter(BaseEntityFieldName.UPDATE_TIME)) {
            this.setFieldValByName(BaseEntityFieldName.UPDATE_TIME, new Date(), metaObject);
        }
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            Long userId = MvcHttpUtil.getCurrAdminId();
            if (metaObject.hasSetter(BaseEntityFieldName.UPDATE_BY) && metaObject.hasGetter(BaseEntityFieldName.UPDATE_BY)) {
                this.setFieldValByName(BaseEntityFieldName.UPDATE_BY, userId, metaObject);
            }
        } catch (Exception ignored) {
        }
        if (metaObject.hasSetter(BaseEntityFieldName.UPDATE_TIME) && metaObject.hasGetter(BaseEntityFieldName.UPDATE_TIME)) {
            this.setFieldValByName(BaseEntityFieldName.UPDATE_TIME, new Date(), metaObject);
        }
    }

}
